package api

import (
	"common/config"
	"errors"
	"fmt"
	"github.com/wangluozhe/requests"
	"github.com/wangluozhe/requests/url"
	"io"
	"os"
	"path/filepath"
	"strings"
)

func Doc2Docx(srcPath string, distPath string) error {
	conf, _ := config.LoadOfficeConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/office/doc2docx")
	req := url.NewRequest()
	files := url.NewFiles()
	fname := filepath.Base(srcPath)
	files.SetFile("file", fname, srcPath, "")
	headers := url.NewHeaders()
	req.Files = files
	req.Headers = headers
	r, err := requests.Post(uri, req)
	if err != nil {
		return err
	}
	ContentType := r.Headers.Get("Content-Type")
	if strings.Contains(ContentType, "json") {
		return errors.New("doc2docx 转换失败")
	}
	fileByte, _ := io.ReadAll(r.Body)
	os.WriteFile(distPath, fileByte, 0666)
	return nil
}

func Docx2Doc(srcPath string, distPath string) error {
	conf, _ := config.LoadOfficeConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/office/docx2doc")
	req := url.NewRequest()
	files := url.NewFiles()
	headers := url.NewHeaders()
	fname := filepath.Base(srcPath)
	files.SetFile("file", fname, srcPath, "")
	req.Files = files
	req.Headers = headers
	r, err := requests.Post(uri, req)
	if err != nil {
		return err
	}
	ContentType := r.Headers.Get("Content-Type")
	if strings.Contains(ContentType, "json") {
		return errors.New("docx2doc 转换失败")
	}
	fileByte, _ := io.ReadAll(r.Body)
	os.WriteFile(distPath, fileByte, 0666)
	return nil
}

func Doc2Pdf(srcPath string, distPath string) error {
	conf, _ := config.LoadOfficeConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/office/doc2pdf")
	req := url.NewRequest()
	files := url.NewFiles()
	headers := url.NewHeaders()
	fname := filepath.Base(srcPath)
	files.SetFile("file", fname, srcPath, "")
	req.Files = files
	req.Headers = headers
	r, err := requests.Post(uri, req)
	if err != nil {
		return err
	}
	ContentType := r.Headers.Get("Content-Type")
	if strings.Contains(ContentType, "json") {
		return errors.New("doc2pdf 转换失败")
	}
	fileByte, _ := io.ReadAll(r.Body)
	os.WriteFile(distPath, fileByte, 0666)
	return nil
}

func Docx2Pdf(srcPath string, distPath string) error {
	conf, _ := config.LoadOfficeConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/office/docx2pdf")
	req := url.NewRequest()
	files := url.NewFiles()
	headers := url.NewHeaders()
	fname := filepath.Base(srcPath)
	files.SetFile("file", fname, srcPath, "")
	req.Files = files
	req.Headers = headers
	r, err := requests.Post(uri, req)
	if err != nil {
		return err
	}
	ContentType := r.Headers.Get("Content-Type")
	if strings.Contains(ContentType, "json") {
		return errors.New("docx2pdf 转换失败")
	}
	fileByte, _ := io.ReadAll(r.Body)
	os.WriteFile(distPath, fileByte, 0666)
	return nil
}
